package com.syuson.biz.pay.web;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.syuson.biz.pay.entity.AllPayInfo;
import com.syuson.biz.pay.service.PayInfoService;
import com.syuson.biz.pay.utils.FileImageUtils;
import com.syuson.biz.pay.utils.QrcodeUtils;

@Controller
@RequestMapping("pay")
public class PayInfoController {
	private static final String AlIBABA = "qr.alipay.com";
	private static final String WEIXIN = "wxp";
	private static final String QQ = "i.qianbao.qq.com";

	@Autowired
	private PayInfoService payInfoService;

	@RequestMapping(value = "/mergeQrCode", method = RequestMethod.POST)
	public String mergeQrCode(Model model, @RequestParam("aliQrcodeImage") CommonsMultipartFile aliQrcodeImage,
			@RequestParam("wxQrcodeImage") CommonsMultipartFile wxQrcodeImage,
			@RequestParam("qqQrcodeImage") CommonsMultipartFile qqQrcodeImage, HttpServletRequest request)
			throws IOException {
		String alipayUrl = "";
		String wechatUrl = "";
		String qqUrl = "";
		int nullNum = 0;
		if ( null == aliQrcodeImage ) {
			nullNum++;
		} else {
			InputStream inputStream = aliQrcodeImage.getInputStream();
			String qrcodeContext = QrcodeUtils.decodeQrcode(inputStream);
			alipayUrl = qrcodeContext.trim();
			qrcodeContext = qrcodeContext.toLowerCase();
			if (!qrcodeContext.contains(AlIBABA)) {
				alipayUrl = "";
				model.addAttribute("status", "99999");
				model.addAttribute("msg", "支付宝收款码错误");
				return "merge-qrcode";
			}
		}
		if ( null == wxQrcodeImage ) {
			nullNum++;
		} else {
			InputStream inputStream = wxQrcodeImage.getInputStream();
			String qrcodeContext = QrcodeUtils.decodeQrcode(inputStream);
			wechatUrl = qrcodeContext.trim();
			qrcodeContext = qrcodeContext.toLowerCase();
			if (!qrcodeContext.contains(WEIXIN)) {
				wechatUrl = "";
				model.addAttribute("status", "99999");
				model.addAttribute("msg", "微信收款码错误");
				return "merge-qrcode";
			}
		}
		if ( null == qqQrcodeImage ) {
			nullNum++;
		} else {
			InputStream inputStream = qqQrcodeImage.getInputStream();
			String qrcodeContext = QrcodeUtils.decodeQrcode(inputStream);
			qqUrl = qrcodeContext.trim();
			qrcodeContext = qrcodeContext.toLowerCase();
			if (!qrcodeContext.contains(QQ)) {
				qqUrl = "";
				model.addAttribute("status", "99999");
				model.addAttribute("msg", "QQ钱包收款码错误");
				return "merge-qrcode";
			}
		}
		if ((nullNum > 0) || (StringUtils.isEmpty(alipayUrl)) || (StringUtils.isEmpty(wechatUrl))
				|| (StringUtils.isEmpty(qqUrl))) {
			model.addAttribute("status", "99999");
			model.addAttribute("msg", "请上传支付宝、微信、QQ钱包三种收款码");
			return "merge-qrcode";
		}
		List<AllPayInfo> allPayInfoList = new ArrayList<AllPayInfo>();
		AllPayInfo allPayInfo = new AllPayInfo();
		allPayInfo.setAlipayUrl(alipayUrl);
		allPayInfo.setWechatUrl(wechatUrl);
		allPayInfo.setQqUrl(qqUrl);
		allPayInfoList.add(allPayInfo);
		if (this.payInfoService.insert(allPayInfoList) > 0) {
			StringBuilder newQrCodeContent = new StringBuilder(request.getScheme());
			newQrCodeContent.append("://").append(request.getServerName()).append(":").append(request.getServerPort())
					.append(request.getContextPath()).append("/");
			newQrCodeContent.append("pay?id=").append(allPayInfo.getId());
			String path = generateQrCode(newQrCodeContent.toString());
			model.addAttribute("status", "10000");
			model.addAttribute("msg", "merge成功");
			model.addAttribute("imagePath", path);
			return "merge-qrcode";
		}
		model.addAttribute("status", "99999");
		model.addAttribute("msg", "merge失败");
		return "merge-qrcode";
	}

	@RequestMapping("")
	public String allpay(Model model, @RequestParam("id") String id, HttpServletRequest request) throws IOException {
		if (StringUtils.isEmpty(id)) {
			model.addAttribute("status", "99999");
			model.addAttribute("msg", "收款码错误");
			return "merge-qrcode";
		}
		AllPayInfo allPayInfo = this.payInfoService.queryById(id);
		if (StringUtils.isEmpty(allPayInfo)) {
			model.addAttribute("status", "99999");
			model.addAttribute("msg", "收款码错误");
			return "merge-qrcode";
		}
		String qqUrl = allPayInfo.getQqUrl();
		String wechatUrl = allPayInfo.getWechatUrl();
		String alipayUrl = allPayInfo.getAlipayUrl();

		String payUrl = "";
		String scanType = "0";
		String userAgent = request.getHeader("user-agent");
		if ( null != userAgent ) {
			userAgent = userAgent.toLowerCase();
			if (userAgent.contains("alipayclient")) {
				payUrl = alipayUrl;
				scanType = "1";
				model.addAttribute("payUrl", payUrl);
			} else if (userAgent.contains("micromessenger")) {
				payUrl = wechatUrl;
				scanType = "2";
			} else if (userAgent.contains("qq")) {
				payUrl = qqUrl;
				scanType = "3";
			} else {
				StringBuilder newQrCodeContent = new StringBuilder(request.getScheme());
				newQrCodeContent.append("://").append(request.getServerName()).append(":")
						.append(request.getServerPort()).append(request.getContextPath()).append("/");
				newQrCodeContent.append("pay?id=").append(id);
				payUrl = newQrCodeContent.toString();
			}
		}
		String path = generateQrCode(payUrl);
		model.addAttribute("scanType", scanType);
		model.addAttribute("imagePath", path);
		return "allpay";
	}

	private String generateQrCode(String content) throws IOException {
		String nameId = UUID.randomUUID().toString().replace("-", "");
		String path = "/upload/" + nameId + ".png";
		String mergeIamge = FileImageUtils.staticFileUploadDir() + path;
		File file = new File(mergeIamge);
		QrcodeUtils.createQrcodeImage(content, Integer.valueOf(300), file);
		return path;
	}
}
